#pragma once

#include <unordered_map>
#include "Socket.hpp"
#include "TcpServer.hpp"
#include "Log.hpp"
#include "Util.hpp"

using namespace SocketModule;
using namespace LogModule;

const std::string gspace = " ";
const std::string glinespace = "\r\n";
const std::string glinesep = ": ";
const std::string webroot = "./wwwroot";
const std::string homepage = "/index.html";
const std::string page_404 = "/404.html";

class HttpRequest
{
public:
    HttpRequest()
        : _is_interact(false)
    {
    }

    std::string Serialize()
    {
        return std::string();
    }

    std::string Uri() { return _uri; }

    void ParseReqLine(std::string &reqline)
    {
        std::stringstream ss(reqline);
        ss >> _method >> _uri >> _version;
    }

    bool Deserialize(std::string &reqstr)
    {
        std::string reqline;
        bool res = Util::ReadOneLine(reqstr, &reqline, glinespace);
        LOG(LogLevel::DEBUG) << reqline;
        ParseReqLine(reqline);
        if (_uri == "/")
            _uri = webroot + homepage;
        else
            _uri = webroot + _uri;

        const std::string temp = "?";
        auto pos = _uri.find(temp);

        if (pos == std::string::npos)
            return true;

        _args = _uri.substr(pos + temp.size());
        _uri = _uri.substr(0, pos);
        _is_interact = true;
        return true;
    }

    bool isInteract()
    {
        return _is_interact;
    }
    std::string Args()
    {
        return _args;
    }

    ~HttpRequest()
    {
    }

private:
    std::string _method;
    std::string _uri;
    std::string _version;

    std::unordered_map<std::string, std::string> _headers;
    std::string _blankline;
    std::string _text;

    bool _is_interact;
    std::string _args;
};

class HttpResponse
{
public:
    HttpResponse()
        : _backline(glinespace),
          _version("HTTP/1.0")
    {
    }

    std::string Serialize()
    {
        std::string status_line = _version + gspace + std::to_string(_code) + gspace + _desc + glinespace;
        std::string resp_header;
        for (auto &header : _headers)
        {
            std::string line = header.first + glinesep + header.second + glinespace;
            resp_header += line;
        }
        return status_line + resp_header + _backline + _text;
    }

    void SetTargetFile(const std::string &target)
    {
        _targetfile = target;
    }

    void SetCode(int code)
    {
        _code = code;
        switch (_code)
        {
        case 200:
            _desc = "OK";
            break;
        case 404:
            _desc = "Not Found";
            break;
        case 302:
            _desc = "See Other";
            break;
        default:
            break;
        }
    }

    void SetHeader(const std::string &key, const std::string &value)
    {
        auto iter = _headers.find(key);
        if (iter != _headers.end())
            return;
        _headers.insert(std::make_pair(key, value));
    }

    std::string Uri2Suffix(std::string &targetfile)
    {
        auto pos = targetfile.rfind(".");
        if (pos == std::string::npos)
            return "text/html";
        std::string suffix = targetfile.substr(pos);
        if (suffix == ".html" || suffix == ".htm")
            return "text/html";
        else if (suffix == ".jpg")
            return "image/jpg";
        else if (suffix == ".png")
            return "image/png";
    }

    bool MakeResponse()
    {
        if (_targetfile == "./wwwroot/favicon.ico")
        {
            return false;
        }

        if (_targetfile == "./wwwroot/redir_test")
        {
            SetCode(302);
            SetHeader("Location", "https://www.qq.com/");
            return true;
        }

        int filesize = 0;
        bool res = Util::ReadFileContent(_targetfile, &_text);
        if (!res)
        {
            _text = "";

            SetCode(404);
            _targetfile = webroot + page_404;
            filesize = Util::FileSize(_targetfile);
            Util::ReadFileContent(_targetfile, &_text);
            SetHeader("Content_Length", std::to_string(filesize));
            std::string suffix = Uri2Suffix(_targetfile);
            SetHeader("Content_Type", suffix);
        }
        else
        {
            SetCode(200);
            filesize = Util::FileSize(_targetfile);
            SetHeader("Content_Length", std::to_string(filesize));
            std::string suffix = Uri2Suffix(_targetfile);
            SetHeader("Content_Type", suffix);
        }
        // SetHeader("Content_Length", std::to_string(filesize));

        return true;
    }

    void SetText(const std::string &t)
    {
        _text = t;
    }

    bool Deserialize(std::string &reqstr)
    {
        return true;
    }

    ~HttpResponse()
    {
    }

public:
    int _code;
    std::string _desc;
    std::string _version;

    std::unordered_map<std::string, std::string> _headers;
    std::string _backline;
    std::string _text;

    std::string _targetfile;
};

using http_func_t = std::function<void(HttpRequest &req, HttpResponse &resp)>;

class Http
{
public:
    Http(uint16_t port)
        : _tsvrp(std::make_unique<TcpServer>(port))
    {
    }

    void HandlerHttpRquest(std::shared_ptr<Socket> &sock, InetAddr &client)
    {
        std::string httprequest;
        int n = sock->Recv(&httprequest);
        if (n > 0)
        {
            HttpRequest req;
            req.Deserialize(httprequest);
            HttpResponse resp;

            if (req.isInteract())
            {
                if (_route.find(req.Uri()) == _route.end())
                {
                }
                else
                {
                    _route[req.Uri()](req, resp);
                    std::string response_str = resp.Serialize();
                    sock->Send(response_str);
                }
            }
            else
            {
                resp.SetTargetFile(req.Uri());
                if (resp.MakeResponse())
                {
                    std::string response_str = resp.Serialize();
                    sock->Send(response_str);
                }
            }

            // HttpResponse resp;
            // resp._version = "HTTP/1.1";
            // resp._code = 200;
            // resp._desc = "OK";
            // bool res = Util::ReadFileContent(filename, &resp._text);
            // (void)res;
        }
        std::cout << httprequest << std::endl;

// #ifndef DEBUG
// #define DEBUG
#ifdef DEBUG
        std::string httprequest;
        sock->Recv(&httprequest);
        std::cout << httprequest << std::endl;

        HttpResponse resp;
        resp._version = "HTTP/1.1";
        resp._code = 200;
        resp._desc = "OK";

        std::string filename = webroot + homepage;

        bool res = Util::ReadFileContent(filename, &resp._text);
        (void)res;

        std::string response_str = resp.Serialize();
        sock->Send(response_str);

#endif
    }

    void Start()
    {
        _tsvrp->Start([this](std::shared_ptr<Socket> &sock, InetAddr &client)
                      { this->HandlerHttpRquest(sock, client); });
    }

    void RegisterService(const std::string name, http_func_t h)
    {
        std::string key = webroot + name;
        auto iter = _route.find(key);
        if (iter == _route.end())
        {
            _route.insert(std::make_pair(key, h));
        }
    }

    ~Http()
    {
    }

private:
    std::unique_ptr<TcpServer> _tsvrp;
    std::unordered_map<std::string, http_func_t> _route;
};